﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using DBLibrary;
using Common;
using System.Web.Security;

public partial class RegisterPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void RegImageButton_Click(object sender, ImageClickEventArgs e)
    {
        if (PoseidonDBHelper.AdminDB.Exist<AdminDBDetail>(new DBParam("AdminName", AdminNameTextBox.Text)))
        {
            return;
        }
        string keyFileContent = string.Empty;
        using (Stream stream = KeyFileUpload.FileContent)
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                keyFileContent = reader.ReadToEnd();
            }
        }
        DB db = PoseidonDBHelper.AdminDB;
        List<KeyDetail> ks = db.Select<KeyDetail>(new DBParam("KeyId", keyFileContent));
        if (ks != null && ks.Count > 0)
        {
            KeyDetail kd = ks[0];
            if (!kd.IsInUse)
            {
                AdminDBDetail ad = new AdminDBDetail();
                ad.AdminName = AdminNameTextBox.Text;
                ad.CompanyName = CompanyNameTextBox.Text;
                ad.Email = EmailTextBox.Text;
                ad.PassWord = Pwd1TextBox.Text;
                ad.RetrieveAnswer = AnswerTextBox.Text;
                ad.RetrieveQuestion = QuestionTextBox.Text;
                ad.KeyId = kd.KeyId;
                db.Insert(ad);

                kd.IsInUse = true;
                kd.DBPre = ad.DBPre;
                if ((kd.UsageType & KeyUsageType.Terminable) == KeyUsageType.Terminable)
                {
                    kd.KeyContent = KeyContent.GenerateKey(kd.KeyContent.MaxDays);
                }
                else if ((kd.UsageType & KeyUsageType.Temporary) == KeyUsageType.Temporary)
                {
                    kd.KeyContent = KeyContent.GenerateKey();
                }
                db.Update(kd, "KeyId");

                this.Session.SetUserDBPrefix(ad.AdminName, ad.DBPre);
                PoseidonDBHelper.CreateNewUserDB(ad.DBPre);
                FormsAuthentication.SetAuthCookie(ad.AdminName, false);

                this.Response.Redirect("~/masterPages/main/MainDefault.aspx");
            }
        }
    }
}